/**
 * 
 */
package com.desksoft.ecommerce.handler.listener;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;


/***************************************
 * 版权所有：杭州迪科软件 保留所有权利
 * 创建日期: 
 * 创建作者：yejw
 * 文件名称：
 * 版本：
 * 功能：
 * 最后修改时间：
 * 修改记录：
 *****************************************/
public class SessionListener implements HttpSessionListener {
    
    protected static Map<ServletContext, Map<String, HttpSession>> 
    				contextMap = new ConcurrentHashMap<ServletContext, Map<String, HttpSession>>();

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpSessionListener#sessionCreated(javax.servlet.http.HttpSessionEvent)
     */
    @Override
    public void sessionCreated(HttpSessionEvent event) {
    	Map<String, HttpSession> sessionMap = contextMap.get(event.getSession().getServletContext());
    	
    	if (sessionMap == null) {
			sessionMap = new ConcurrentHashMap<String, HttpSession>();
			contextMap.put(event.getSession().getServletContext(), sessionMap);
		}
    	
    	sessionMap.put(event.getSession().getId(), event.getSession());
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpSessionListener#sessionDestroyed(javax.servlet.http.HttpSessionEvent)
     */
    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
    	Map<String, HttpSession> sessionMap = contextMap.get(event.getSession().getServletContext());
    	
    	if (sessionMap != null) {
			sessionMap.remove(event.getSession().getId());
		}
    }
    
    /**
     * 获取SESSION
     * 
     * @param context
     * @param id
     * @return
     */
    public static HttpSession getSession(ServletContext context, String id){
    	Map<String, HttpSession> sessionMap = contextMap.get(context);
    	
		if (sessionMap != null) {
			return sessionMap.get(id);
		}
		
		return null;
    }
}

